<template>
    <div class="common-layout">
        <el-container>
            <el-aside width="200px">
                <el-tree ref="treeRef" style="max-width: 600px" class="filter-tree" :data="data" :props="defaultProps"
                    default-expand-all :filter-node-method="filterNode" @node-click="jump" />
            </el-aside>
            <el-main style="padding: 0px;">
                <div class="common-layout">
                    <el-container>
                        <el-header>
                            <div class="statistics-container">
                                <h3>设备类型统计</h3>
                                <div class="statistics-cards">
                                    <el-card v-for="(count, type) in deviceTypeStats" :key="type" class="stat-card">
                                        <div class="stat-content">
                                            <span class="stat-label">{{ type }}</span>
                                            <span class="stat-value">{{ count }}</span>
                                        </div>
                                    </el-card>
                                </div>
                            </div>
                        </el-header>
                        <el-main style="margin-top: 100px;">
                            <el-button type="primary" v-if="id != null" @click="add">添加</el-button>
                            <el-button type="primary" v-if="id == null" disabled>添加</el-button>
                            <el-button type="info" @click="resetView">重置</el-button>
                            <el-table :data="tableData" border style="width: 100%">
                                <el-table-column type="index" label="序号" width="55px" />
                                <el-table-column prop="devicetype" label="设备类型" />
                                <el-table-column prop="deviceNo" label="设备编号" />
                                <el-table-column prop="state" label="状态">
                                    <template #default="scope">
                                        <el-tag type="primary" v-if="scope.row.state == 1">正常</el-tag>
                                        <el-tag type="primary" v-if="scope.row.state == 2">电量低</el-tag>
                                        <el-tag type="primary" v-if="scope.row.state == 3">异常离线</el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作">
                                    <template #default="scope">
                                        <el-button type="warning" @click="edit(scope.row.id,scope.row.nursingUnitId)">编辑</el-button>
                                        <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-main>
                    </el-container>
                </div>
            </el-main>
        </el-container>
    </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, watch, onBeforeMount, computed } from 'vue';
import { ElMessage, type TreeInstance, ElMessageBox } from 'element-plus'
import { useRouter, onBeforeRouteUpdate } from 'vue-router'
import http from "@/api/http";
const router = useRouter();
onMounted(() => {
    showtree()
    show()
})

// Add navigation guard to refresh data when returning to this page
onBeforeRouteUpdate((to, from) => {
    // If coming from edit page, refresh the data
    if (from.path === '/EditEquipment') {
        show()
    }
    // If coming from add page, reset id and show all data
    if (from.path === '/AddEquipment') {
        id.value = null
        show()
    }
})

// Also add a watch on the route to handle direct navigation
watch(() => router.currentRoute.value, (newRoute, oldRoute) => {
    if (oldRoute.path === '/EditEquipment') {
        show()
    }
    if (oldRoute.path === '/AddEquipment') {
        id.value = null
        show()
    }
}, { immediate: false })

// Define interface for equipment item
interface EquipmentItem {
    id: string | number;
    devicetype: string;
    deviceNo: string;
    state: number;
    nursingUnitId: string | number;
}

// Compute device type statistics
const deviceTypeStats = computed(() => {
    const stats: Record<string, number> = {}
    if (tableData.value && tableData.value.length > 0) {
        tableData.value.forEach((item: EquipmentItem) => {
            if (item.devicetype) {
                stats[item.devicetype] = (stats[item.devicetype] || 0) + 1
            }
        })
    }
    return stats
})

const del = (id: string | number) => {
    ElMessageBox.confirm(
    '确定删除吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
        http.post(`/api/EquipmentSomeThing/DelEquipment?id=${id}`)
        .then(res => {
            ElMessage.success('删除成功')
            show()
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
   
}

const add = () => {
    router.push({
        path: '/AddEquipment',
        query: {
            id: id.value
        }
    })
}

const edit = (id: string | number, nursingUnitId: string | number) => {
    console.log("这个",id,nursingUnitId)
    router.push({
        path: '/EditEquipment',
        query: {
            id: id,
            nursingUnitId: nursingUnitId,
            _t: Date.now()
        }
    })
}
const jump = (a: any) => {
    id.value = a.id
    show()
}

let id = ref(null)
let level = ref(0)

interface Tree {
    [key: string]: any
}
const filterText = ref('')
const treeRef = ref<TreeInstance>()

const defaultProps = {
    children: 'children',
    label: 'name',
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
    if (!value) return true
    return data.label.includes(value)
}

const data: any = ref([])

const showtree = () => {
    http.get(
        '/api/EquipmentSomeThing/ShowTree'
    )
        .then(res => {
            data.value = res.data
            console.log(res)
        })
}
const show = () => {
    console.log(id.value)
    http.get(`/api/EquipmentSomeThing/ShowEquipment?nursingUnitId=`+id.value)
        .then(res => {
            tableData.value = res.data
        })
}

const resetView = () => {
    id.value = null
    level.value = 0
    show()
}

const tableData = ref<EquipmentItem[]>([])
</script>

<style scoped>
.statistics-container {
    padding: 8px;
    background-color: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 10px;
}

.statistics-container h3 {
    margin-top: 0;
    margin-bottom: 10px;
    color: #303133;
    font-size: 16px;
}

.statistics-cards {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.stat-card {
    min-width: 120px;
    margin-bottom: 5px;
}

.stat-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 5px;
}

.stat-label {
    font-size: 12px;
    color: #606266;
    margin-bottom: 3px;
}

.stat-value {
    font-size: 18px;
    font-weight: bold;
    color: #409EFF;
}
</style>